﻿using System.Collections.Generic;
using System.Xml;

namespace ActiveStory.IO
{
    public class XmlMapFileReader<TKey,TValue> : IMapFileReader<TKey,TValue>
    {
        #region IMapFileReader<TKey,TValue> Members

        public IDictionary<TKey, TValue> ParseFile(string filename, string mainElementName, string mapItemElementName, string keyElementName, string valueElementName)
        {
            IDictionary<TKey, TValue> loadedMap = new Dictionary<TKey, TValue>();
            XmlReaderSettings xrs = new XmlReaderSettings();
            xrs.CloseInput = true;
            XmlReader xr = XmlReader.Create(filename, xrs);
            xr.ReadStartElement(mainElementName);
            if (xr.NodeType == XmlNodeType.None)
            {
                xr.Close();
                return loadedMap;
            }
            while (!xr.EOF && xr.Read())
            {
                if (xr.Name.Equals(mainElementName))
                    break;
                xr.ReadStartElement(mapItemElementName);
                xr.ReadStartElement(keyElementName);
                TKey keyValue = (TKey)xr.ReadContentAs(typeof(TKey), null);
                xr.ReadEndElement();
                xr.ReadStartElement(valueElementName);
                loadedMap.Add(keyValue, (TValue)xr.ReadContentAs(typeof(TValue),null));
                xr.ReadEndElement();
                xr.ReadEndElement();
            }
            xr.ReadEndElement();
            xr.Close();
            return loadedMap;
        }

        #endregion
    }
}
